package com.example.tmxk.selvlet;

import com.example.tmxk.bean.NewsBean;
import com.example.tmxk.dao.NewsDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/news.jsp")
public class NoticeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String p = req.getParameter("page"); //获取用户传递过来的页码
        int page = 1; // 默认页码是1
        if (p != null && p.equals("")) {
            page = Integer.parseInt(p); //字符串转整数
        }
        // todo获取分页页码参数
        // 获取新闻信息
        // 传递新闻信息给前端页面
        //加载显示前端页面
        NewsDao dao = new NewsDao();
        List<NewsBean> NewsBean = NewsDao.getList(page);
        // 给用户总条数 和 页数
        int totalCount,curPage,totalPage,upPage,downPage;
        totalCount = NewsDao.count(); // 总条数
        curPage = page; // 用户传递进来的页码
        if (totalCount %10 == 0) { //能除尽 页码不加1
            totalPage = totalCount / 10;
        }else {
            totalPage = totalCount / 10 + 1; // 计算总页数
        }
        //上一页 当前页数减去1
        if (curPage == 1){
            upPage = 1;
        }else {
            upPage = curPage - 1;
        }
        if (curPage == totalPage){ // 当前页和总页数 相同下一页 不加1
            downPage = totalPage;
        }else {
            downPage = curPage + 1;
        }
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("curPage", curPage);
        req.setAttribute("totalPage", totalPage);
        req.setAttribute("upPage", upPage);
        req.setAttribute("downPage", downPage);
        req.setAttribute("news", NewsBean);
        req.getRequestDispatcher("news.jsp").forward(req, resp);

    }
}
